<template>
  <div class="h-full">
    <div class="w-full px-4 py-3 flex items-center gap-4 text-white task-panel">
      <div class="flex items-center gap-4 flex-1">
        <div class="flex items-center gap-2">
          <span class="text-sm text-gray-400">时间:</span>
          <el-date-picker
            v-model="searchParams.time"
            type="datetimerange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            @change="handleTimeChange"
          />
        </div>
        <div class="flex items-center gap-2">
          <span class="text-sm text-gray-400">图片类型:</span>
          <el-select
            v-model="searchParams.photoType"
            placeholder="请选择查询图片类型"
            class="width-common"
            @change="handlePhotoTypeChange"
          >
            <el-option v-for="item in photoTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </div>

        <div class="flex items-center gap-2">
          <span class="text-sm text-gray-400">计划名称:</span>
          <el-input
            v-model="searchParams.jobName"
            class="width-common"
            placeholder="请输入计划名称"
            @keypress.enter="getFiles({ job_name: searchParams.jobName })"
          />
        </div>

        <div class="flex items-center gap-2">
          <span class="text-sm text-gray-400">负载类型:</span>
          <el-select
            v-model="searchParams.payloadModelKey"
            placeholder="请选择查询载具类型"
            class="width-common"
            @change="getFiles({ payload_model_key: searchParams.payloadModelKey })"
          >
            <el-option v-for="item in DeviceOption" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </div>
      </div>
      <el-button type="primary" @click="resetClick">重置</el-button>
    </div>

    <div class="media-panel-wrapper">
      <el-table :data="mediaData.data" border style="width: 100%" height="650">
        <el-table-column prop="file_name" label="文件名称" width="330" />
        <el-table-column prop="drone" label="无人机类型" width="210" />
        <el-table-column prop="payload" label="载具类型" width="130" />
        <el-table-column prop="job_name" label="任务名称"></el-table-column>
        <el-table-column prop="wayline_name" label="航线名称" width="210" />

        <el-table-column prop="is_original" label="原图" width="60">
          <template #default="text"> {{ text ? '是' : '否' }} </template>
        </el-table-column>
        <el-table-column prop="create_time" label="创建时间" width="180" />
        <el-table-column prop="signed_url" label="预览" width="120">
          <template #default="{ row }">
            <img :src="row.signed_url" alt="" class="cursor-pointer w-10 h-10" @click="previewMedia(row)" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <a-tooltip title="下载">
              <a-button type="primary" @click="downloadMedia(scope.row)"> 下载 </a-button>
            </a-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <div class="flex justify-end mt-6">
        <el-pagination
          v-model:current-page="paginationProp.current"
          v-model:page-size="paginationProp.pageSize"
          :page-sizes="paginationProp.pageSizeOptions"
          :size="size"
          :disabled="disabled"
          :background="background"
          layout="total, sizes, prev, pager, next, jumper"
          :total="paginationProp.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <mediaPreview
      v-if="previewVisible"
      :mediaUrl="currentMediaUrl"
      :mediaInfo="currentMediaInfo"
      v-model:visible="previewVisible"
      :mediaList="mediaData.data"
    />
  </div>
</template>

<script setup lang="ts">
import { MediaType, photoTypeOptions } from '@/types/media'
import { Pagination } from 'ant-design-vue'
import { TableState } from 'ant-design-vue/lib/table/interface'
import { ComponentSize } from 'element-plus'
import { onMounted, reactive } from 'vue'
import { IPage } from '../api/http/type'
import { DeviceOption } from '../types/device'
import { ELocalStorageKey } from '../types/enums'
import { downloadMediaFile, getMediaFiles } from '@/api/media'
import { sessionStorage } from '@/utils/storage'
import { downloadFile } from 'sunrise-utils'
import { reduce } from 'lodash'
import store from '../store'
const workspaceId = sessionStorage.get(ELocalStorageKey.WorkspaceId)!
const loading = ref(false)

const previewVisible = ref(false)
const currentMediaUrl = ref('') // 当前媒体文件地址
const currentMediaInfo = ref({}) // 当前媒体的详细信息
let searchParams = reactive({
  time: [],
  mediaType: '',
  photoType: '',
  payloadModelKey: '',
  jobName: ''
})
const resetClick = () => {
  searchParams = {
    time: [],
    mediaType: '',
    photoType: '',
    payloadModelKey: '',
    jobName: ''
  }
  store.commit('SET_MEDIA_TYPE', 0)
  getFiles()
}
// const handlerDateClear = () => {
//   console.log(12)
// }
const handlePhotoTypeChange = (key: MediaType) => {
  console.log(key, 'key')
  getFiles({ photo_type: key })
}

const currentPage = ref(4)
const pageSize = ref(100)
const size = ref<ComponentSize>('default')
const background = ref(false)
const disabled = ref(false)

const handleSizeChange = () => {
  getFiles()
}
const handleCurrentChange = () => {
  getFiles()
}
const handleTimeChange = () => {
  console.log(searchParams.time, 'time')
  if (searchParams?.time?.length > 0) {
    const start = new Date(searchParams.time[0]).getTime()
    const end = new Date(searchParams.time[1]).getTime()
    getFiles({ begin_time: start, end_time: end })
  } else {
    getFiles()
  }
}

const mediaUrl = ref('')
const previewMedia = (record: any) => {
  console.log(record, 'previewMedia')
  currentMediaInfo.value = { ...record }
  currentMediaUrl.value = record.src_signed_url
  mediaUrl.value = record.signed_url
  requestAnimationFrame(() => {
    previewVisible.value = true
  })
}
const body: IPage = {
  page: 1,
  total: 0,
  page_size: 50
}
const paginationProp = reactive({
  pageSizeOptions: [10, 20, 50, 100],
  showQuickJumper: true,
  showSizeChanger: true,
  pageSize: 10,
  current: 1,
  total: 0
})

type Pagination = TableState['pagination']

interface MediaFile {
  fingerprint: string
  drone: string
  payload: string
  is_original: string
  file_name: string
  file_path: string
  create_time: string
  file_id: string
}

const mediaData = reactive({
  data: [] as MediaFile[]
})

onMounted(() => {
  getFiles()
})
watch(
  () => store.state.mediaType,
  (newVal) => {
    if (newVal !== 0) {
      getFiles({ media_type: newVal })
    }
  },
  { deep: true }
)

const getFiles = (parmas: any = {}) => {
  const newParams = { page: paginationProp.current, page_size: paginationProp.pageSize, ...parmas }
  getMediaFiles(workspaceId, newParams).then((res) => {
    mediaData.data = res.data.list
    paginationProp.total = res.data.pagination.total
    paginationProp.current = res.data.pagination.page
    console.info(mediaData.data[0], '======================1=11=1==')
    store.dispatch('setMediaInfo', {
      total_photo_num: res.data.pagination.total_photo_num,
      total_video_num: res.data.pagination.total_video_num,
      total_photo_size: res.data.pagination.total_photo_size,
      total_video_size: res.data.pagination.total_video_size
    })
  })
}

function refreshData(page: Pagination) {
  body.page = page?.current!
  body.page_size = page?.pageSize!
  getFiles()
}

function downloadMedia(media: MediaFile) {
  loading.value = true
  // 一个标准的图片链接进行下载
  // const res = media.signed_url.replace('https', 'http')
  // console.log(res, 'res')
  // downloadImage('https://vip.chaoyang1024.top/20241018105059_strawberries-8295645.jpg', media.file_name)
  downloadMediaFile(workspaceId, media.file_id)
    .then(async (res) => {
      // if (!res) {
      //   return
      // }
      // await downloadFile(res.data, media.file_name)

      await downloadImage(res.data, media.file_name)
    })
    .finally(() => {
      loading.value = false
    })
}
async function downloadImage(imageUrl: string, filename: string) {
  try {
    // 使用 fetch 获取文件内容
    const response = await fetch(imageUrl)
    if (!response.ok) {
      throw new Error(`Failed to fetch image: ${response.statusText}`)
    }
    // console.log(response, 'response')
    // const contentType = response.headers.get('content-type')
    // console.log(contentType, 'contentType')
    // if (
    //   !contentType?.startsWith('application/octet-stream') &&
    //   !contentType?.includes('application/zip') &&
    //   !contentType?.startsWith('image/')
    // ) {
    //   throw new Error('下载失败：服务器返回非文件类型内容')
    // }
    // 将文件内容转换为 Blob
    const blob = await response.blob()

    // 创建一个指向 Blob 的临时 URL
    const blobUrl = URL.createObjectURL(blob)

    // 创建 <a> 标签并触发下载
    const aTag = document.createElement('a')
    aTag.href = blobUrl
    aTag.download = filename // 设置下载的文件名
    document.body.appendChild(aTag) // 将 <a> 标签添加到文档中
    aTag.click() // 触发点击事件
    document.body.removeChild(aTag) // 移除 <a> 标签

    // 释放 Blob URL
    URL.revokeObjectURL(blobUrl)
  } catch (error) {
    console.error('Error downloading image:', error)
  }
}
</script>

<style lang="scss" scoped>
.media-panel-wrapper {
  width: 100%;
  background: rgba(3, 5, 7, 0.9);
  padding: 16px;
  height: 100%;
}

.header {
  width: 100%;
  height: 60px;
  background: #fff;
  padding: 16px;
  font-size: 20px;
  font-weight: bold;
  text-align: start;
  color: #000;
}

.task-panel {
  background: rgba(8, 16, 26, 0.8);
  /* 调整背景颜色，并增加透明度 */
  border: 1px solid #333;
  /* 添加边框 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);

  /* 添加阴影效果 */
  .width-common {
    width: vw(168);
    background-color: rgba(48, 48, 48, 0.3);
    border: 1px solid #dbdbdb;
    border-radius: 4px;
  }
}

:deep(.preview) {
  .el-dialog {
    border: 1px solid rgba(219, 219, 219, 0.5);

    .el-dialog__header {
      height: 42px;
      background-color: rgba(0, 0, 1, 0.5);
      border-bottom: 1px solid rgba(219, 219, 219, 0.5);
      display: flex;
      align-items: center;
    }

    .el-dialog__body {
      padding: 0;
      margin: 10px 0 0 0;
    }
  }
}
</style>
